package deepbitview

import javax.net.ssl.SSLContext
import javax.net.ssl.HttpsURLConnection

/**
 * this is a service which access global statistics about the bit coin network
 * it parses the bitcoincharts.com homepage and extract elements from it
 */
class GlobalStatsService {

    static transactional = true

    /**
     * fetches the global stats from the webpage
     */
    Map fetchGlobalStats() {

        TrustManager[] trustAllCerts = new TrustManager[1]

        trustAllCerts[0] = new TrustManager()
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
        }

        //parse our data to a json object
        Scanner scanner = new Scanner(new URL("http://bitcoincharts.com/markets/").openStream())

        def result = [:]

        while (scanner.hasNextLine()) {

            String line = scanner.nextLine()

//extracting the difficulty value
            if (line.matches(/.*\<tr\>\<td class="label">Difficulty<\/td><td>[0-9].*<\/td><\/tr>.*/)) {
                def m = line =~ /[0-9]+/
                result["difficulty"] = Long.parseLong(m[0].toString())
            }
//extracting the difficulty value
            if (line.matches(/.*\<tr\>\<td class="label">Estimated<\/td><td>[0-9]+.*in.*blks<\/td><\/tr>.*/)) {
                def m = line =~ /[0-9]+/
                result["difficulty_estimate"] = Long.parseLong(m[0].toString())
            }

            //extracting the blocks value
            if (line.matches(/.*<tr><td class="label">Blocks<\/td><td>[0-9].*<\/td><\/tr>.*/)) {
                def m = line =~ /[0-9]+/
                result["blocks"] = Long.parseLong(m[0].toString())
            }

//extracting the bitcoins value
            if (line.matches(/.*<tr><td class="label">Total BTC<\/td><td>[0-9]+\.[0-9]+<\/td><\/tr>.*/)) {
                def m = line =~ /[0-9]+\.[0-9]+/
                result["bitcoins_total"] = Double.parseDouble(m[0].toString())*1000000
            }
//extracting the network value
            if (line.matches(/.*<tr><td class="label">Network total<\/td><td>[0-9]+\.[0-9]+.*<\/td><\/tr>.*/)) {
                def m = line =~ /[0-9]+\.[0-9]+/
                result["network_speed"] = Double.parseDouble(m[0].toString())
            }
        }
        return result
    }
}
